﻿using Md.Api.DDD;
using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Web.MdUser.Request;
using Md.Dapper.Repositories.Md;
using Md.Redis.Repositories;

namespace Md.Api.Service.Web.MdUser;
/// <summary>
/// 用户登录服务
/// </summary>
public class LoginMdUserWebService : ApiBase<RequestLoginMdUserWebModel>
{
    /// <summary>
    /// 用户仓储
    /// </summary>
    public MdUserRep mdUserRep { get; set; }
    /// <summary>
    /// redis缓存
    /// </summary>
    public MdRedisService _redisService { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        MdUserModel? user = null;

        if (Parameter.LoginMode == "1")
        {
            if (string.IsNullOrWhiteSpace(Parameter.UserName))
            {
                Result.Data = "userName is empty";
                return;
                // throw new AggregateException("用户名不能为空");
            }

            user = mdUserRep.Login(Parameter.UserName, EncrptyHelp.MD5Pwd(Parameter.UserPwd));
        }

        if (Parameter.LoginMode == "2")
        {
            if (string.IsNullOrWhiteSpace(Parameter.Email))
            {
                Result.Data = "email is empty";
                return;
                // throw new AggregateException("邮箱不能为空");
            }

            user = mdUserRep.LoginEmail(Parameter.Email, EncrptyHelp.MD5Pwd(Parameter.UserPwd));
        }

        if (Parameter.LoginMode == "3")
        {
            if (string.IsNullOrWhiteSpace(Parameter.Phone))
            {
                Result.Data = "phone is empty";
                return;
                // throw new AggregateException("手机号不能为空");
            }

            user = mdUserRep.LoginPhone(Parameter.Phone, EncrptyHelp.MD5Pwd(Parameter.UserPwd));
        }

        if (user == null)
        {
            Result.Data = "not exist";
            return;
            // throw new AggregateException("用户不存在或用户名密码错误");
        }

        if (user.Status == "1")
        {
            Result.Data = "deactivated";
            return;
            // throw new AggregateException("用户已停用,请联系管理员");
        }

        // uuid需要存缓存，uuid对应用户信息
        var uuid = Guid.NewGuid().ToString();

        var userDict = new Dictionary<string, object>
        {
            { "userId", user.UserId},
            { "uuid", uuid },
            { "platform", 2 }
        };

        _redisService.Instance.Set($"{user.UserId}_{userDict["platform"]}", uuid);

        var token = JwtHelp.SetJwtEncode(userDict, Convert.ToDouble(JsonConfig.JsonRead("MdSettings:TokenExpire")));

        _redisService.Instance.Set($"{user.UserId}Token_{userDict["platform"]}", token);

        Result.Data = new { user, token };
    }
}

